﻿#region Includes
using System;
using System.Collections.Generic;
using OpenTK;
#endregion

namespace GingerGL.Math
{
    [Serializable]
    public class BoundingBox : IEquatable<BoundingBox>
    {
        #region Variables
        /// <summary>
        /// Gets/Sets Min Bounding Box Point
        /// </summary>
        public Vector3 Min { get; set; }
        /// <summary>
        /// Gets/Sets Max Bounding Box Point
        /// </summary>
        public Vector3 Max { get; set; }
        /// <summary>
        /// Empty Bounding Box
        /// </summary>
        static public readonly BoundingBox Empty = new BoundingBox(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of object
        /// </summary>
        public BoundingBox() : this(Vector3.Zero, Vector3.Zero) { }
        /// <summary>
        /// Initializes a new instance of object
        /// </summary>
        public BoundingBox(Vector3 min, Vector3 max)
        {
            Min = min;
            Max = max;
        }
        #endregion

        #region Methods
        public ContainmentType Contains(BoundingBox box)
        {
            if (box == null) throw new ArgumentNullException("Parameter can not be null");

            //test if all corner is in the same side of a face by just checking min and max
            if (box.Max.X < Min.X
                || box.Min.X > Max.X
                || box.Max.Y < Min.Y
                || box.Min.Y > Max.Y
                || box.Max.Z < Min.Z
                || box.Min.Z > Max.Z)
                return ContainmentType.Disjoint;

            if (box.Min.X >= Min.X
                && box.Max.X <= Max.X
                && box.Min.Y >= Min.Y
                && box.Max.Y <= Max.Y
                && box.Min.Z >= Min.Z
                && box.Max.Z <= Max.Z)
                return ContainmentType.Contains;


            return ContainmentType.Intersects;
        }
        public ContainmentType Contains(BoundingFrustum frustum)
        {
            if (frustum == null) throw new ArgumentNullException("Parameter can not be null");
            //TODO: bad done here need a fix. 
            //Because question is not frustum contain box but reverse and this is not the same
            int i;
            ContainmentType contained;
            Vector3[] corners = frustum.GetCorners();


            // First we check if frustum is in box
            for (i = 0; i < corners.Length; i++)
            {
                contained = this.Contains(corners[i]);
                if (contained == ContainmentType.Disjoint) break;
            }


            if (i == corners.Length) // This means we checked all the corners and they were all contain or instersect
                return ContainmentType.Contains;


            if (i != 0)             // if i is not equal to zero, we can fastpath and say that this box intersects
                return ContainmentType.Intersects;




            // If we get here, it means the first (and only) point we checked was actually contained in the frustum.
            // So we assume that all other points will also be contained. If one of the points is disjoint, we can
            // exit immediately saying that the result is Intersects
            i++;
            for (; i < corners.Length; i++)
            {
                contained = this.Contains(corners[i]);
                if (contained != ContainmentType.Contains)
                    return ContainmentType.Intersects;


            }


            // If we get here, then we know all the points were actually contained, therefore result is Contains
            return ContainmentType.Contains;
        }
        public ContainmentType Contains(BoundingSphere sphere)
        {
            if (sphere.Center.X - Min.X > sphere.Radius
                && sphere.Center.Y - Min.Y > sphere.Radius
                && sphere.Center.Z - Min.Z > sphere.Radius
                && Max.X - sphere.Center.X > sphere.Radius
                && Max.Y - sphere.Center.Y > sphere.Radius
                && Max.Z - sphere.Center.Z > sphere.Radius)
                return ContainmentType.Contains;


            double dmin = 0;


            if (sphere.Center.X - Min.X <= sphere.Radius)
                dmin += (sphere.Center.X - Min.X) * (sphere.Center.X - Min.X);
            else if (Max.X - sphere.Center.X <= sphere.Radius)
                dmin += (sphere.Center.X - Max.X) * (sphere.Center.X - Max.X);
            if (sphere.Center.Y - Min.Y <= sphere.Radius)
                dmin += (sphere.Center.Y - Min.Y) * (sphere.Center.Y - Min.Y);
            else if (Max.Y - sphere.Center.Y <= sphere.Radius)
                dmin += (sphere.Center.Y - Max.Y) * (sphere.Center.Y - Max.Y);
            if (sphere.Center.Z - Min.Z <= sphere.Radius)
                dmin += (sphere.Center.Z - Min.Z) * (sphere.Center.Z - Min.Z);
            else if (Max.Z - sphere.Center.Z <= sphere.Radius)
                dmin += (sphere.Center.Z - Max.Z) * (sphere.Center.Z - Max.Z);


            if (dmin <= sphere.Radius * sphere.Radius)
                return ContainmentType.Intersects;


            return ContainmentType.Disjoint;
        }
        public ContainmentType Contains(Vector3 point)
        {
            //first we get if point is out of box
            if (point.X < this.Min.X
                || point.X > this.Max.X
                || point.Y < this.Min.Y
                || point.Y > this.Max.Y
                || point.Z < this.Min.Z
                || point.Z > this.Max.Z)
            {
                return ContainmentType.Disjoint;
            }//or if point is on box because coordonate of point is lesser or equal
            else if (point.X == this.Min.X
                || point.X == this.Max.X
                || point.Y == this.Min.Y
                || point.Y == this.Max.Y
                || point.Z == this.Min.Z
                || point.Z == this.Max.Z)
                return ContainmentType.Intersects;
            else
                return ContainmentType.Contains;
        }
        static public BoundingBox CreateFromPoints(IEnumerable<Vector3> points)
        {
            if (points == null) throw new ArgumentNullException();

            // TODO: Just check that Count > 0
            bool empty = true;
            Vector3 vector2 = Vector3.Zero;
            Vector3 vector1 = Vector3.Zero;
            foreach (Vector3 vector3 in points)
            {
                if (vector2 == Vector3.Zero)
                {
                    vector2 = new Vector3(vector3);
                    vector1 = new Vector3(vector3);
                }
                else
                {
                    vector2 = Vector3.Min(vector2, vector3);
                    vector1 = Vector3.Max(vector1, vector3);

                }
                empty = false;
            }

            if (empty) throw new ArgumentException("Error?");
            return new BoundingBox(vector2, vector1);
        }
        public static BoundingBox CreateFromSphere(BoundingSphere sphere)
        {
            Vector3 vector1 = new Vector3(sphere.Radius, sphere.Radius, sphere.Radius);
            return new BoundingBox(sphere.Center - vector1, sphere.Center + vector1);
        }
        public static BoundingBox CreateFromCylinderXY(BoundingCylinderXY cylinder)
        {
            Vector3 vector1 = new Vector3(cylinder.Radius, cylinder.Radius, cylinder.Radius);
            BoundingBox box = new BoundingBox(new Vector3(cylinder.Center) - vector1, new Vector3(cylinder.Center) + vector1);
            box.Max = new Vector3(box.Max.X, box.Max.Y, cylinder.MaxZ);
            box.Min = new Vector3(box.Min.X, box.Min.Y, cylinder.MinZ);
            return box;
        }
        public static BoundingBox CreateMerged(BoundingBox original, BoundingBox additional)
        {
            return new BoundingBox(
                Vector3.Min(original.Min, additional.Min), Vector3.Max(original.Max, additional.Max));
        }
        public bool Equals(BoundingBox other)
        {
            return (this.Min == other.Min) && (this.Max == other.Max);
        }
        public override bool Equals(object obj)
        {
            return (obj is BoundingBox) ? this.Equals((BoundingBox)obj) : false;
        }
        public Vector3[] GetCorners()
        {
            return new Vector3[] {
                new Vector3(this.Min.X, this.Max.Y, this.Max.Z), 
                new Vector3(this.Max.X, this.Max.Y, this.Max.Z),
                new Vector3(this.Max.X, this.Min.Y, this.Max.Z), 
                new Vector3(this.Min.X, this.Min.Y, this.Max.Z), 
                new Vector3(this.Min.X, this.Max.Y, this.Min.Z),
                new Vector3(this.Max.X, this.Max.Y, this.Min.Z),
                new Vector3(this.Max.X, this.Min.Y, this.Min.Z),
                new Vector3(this.Min.X, this.Min.Y, this.Min.Z)
            };
        }
        public override int GetHashCode()
        {
            return this.Min.GetHashCode() + this.Max.GetHashCode();
        }
        public bool Intersects(BoundingBox box)
        {
            if ((this.Max.X >= box.Min.X) && (this.Min.X <= box.Max.X))
                if ((this.Max.Y < box.Min.Y) || (this.Min.Y > box.Max.Y)) { return false; }
                else return (this.Max.Z >= box.Min.Z) && (this.Min.Z <= box.Max.Z); 
            return false;
        }
        public bool Intersects(BoundingFrustum frustum)
        {
            return frustum.Contains(this) != ContainmentType.Disjoint;
        }
        public bool Intersects(BoundingSphere sphere)
        {
            if (sphere.Center.X - Min.X > sphere.Radius
                && sphere.Center.Y - Min.Y > sphere.Radius
                && sphere.Center.Z - Min.Z > sphere.Radius
                && Max.X - sphere.Center.X > sphere.Radius
                && Max.Y - sphere.Center.Y > sphere.Radius
                && Max.Z - sphere.Center.Z > sphere.Radius)
                return true;

            double dmin = 0;

            if (sphere.Center.X - Min.X <= sphere.Radius)
                dmin += (sphere.Center.X - Min.X) * (sphere.Center.X - Min.X);
            else if (Max.X - sphere.Center.X <= sphere.Radius)
                dmin += (sphere.Center.X - Max.X) * (sphere.Center.X - Max.X);


            if (sphere.Center.Y - Min.Y <= sphere.Radius)
                dmin += (sphere.Center.Y - Min.Y) * (sphere.Center.Y - Min.Y);
            else if (Max.Y - sphere.Center.Y <= sphere.Radius)
                dmin += (sphere.Center.Y - Max.Y) * (sphere.Center.Y - Max.Y);


            if (sphere.Center.Z - Min.Z <= sphere.Radius)
                dmin += (sphere.Center.Z - Min.Z) * (sphere.Center.Z - Min.Z);
            else if (Max.Z - sphere.Center.Z <= sphere.Radius)
                dmin += (sphere.Center.Z - Max.Z) * (sphere.Center.Z - Max.Z);

            if (dmin <= sphere.Radius * sphere.Radius)
                return true;

            return false;
        }
        public PlaneIntersectionType Intersects(Plane plane)
        {
            //check all corner side of plane
            Vector3[] corners = this.GetCorners();
            float lastdistance = Vector3.Dot(plane.Normal, corners[0]) + plane.D;

            for (int i = 1; i < corners.Length; i++)
            {
                float distance = Vector3.Dot(plane.Normal, corners[i]) + plane.D;
                if ((distance <= 0.0f && lastdistance > 0.0f) || (distance >= 0.0f && lastdistance < 0.0f))
                    return PlaneIntersectionType.Intersecting;
                lastdistance = distance;
            }

            if (lastdistance > 0.0f)
                return PlaneIntersectionType.Front;

            return PlaneIntersectionType.Back;
        }
        public Nullable<float> Intersects(Ray ray)
        {
            return ray.Intersects(this);
        }
        public override string ToString()
        {
            return string.Format("{{Min:{0} Max:{1}}}", this.Min.ToString(), this.Max.ToString());
        }
        #endregion

        #region Operators
        /// <summary>
        /// ==
        /// </summary>
        public static bool operator ==(BoundingBox left, BoundingBox right)
        {
            return left.Equals(right);
        }
        /// <summary>
        /// !=
        /// </summary>
        public static bool operator !=(BoundingBox left, BoundingBox right)
        {
            return !left.Equals(right);
        }
        #endregion
    }
}
